<?php
namespace zake\foundation\point;

use zake\foundation\able\ProtocolAble;
use zake\foundation\able\reactor\ConnectAble;
use zake\foundation\able\stream\ReadBufferAble;


/**
 * Class Eol
 * @package zake\server\eol
 * 
 * @author liu.bin 2020-04-28 16:01
 */
class Eol implements ProtocolAble
{
    /**
     * @var Eol | null
     */
    private static $singleton = null;


    /**
     * 构造器
     *
     * @author liu.bin 2020-04-03 23:16
     */
    public static function singleton()
    {
        if(is_null(static::$singleton)){
            static::$singleton = new static();
        }
        return static::$singleton;
    }



    /**
     * 计算frameLength
     *
     * @param string $buffer
     * @param ReadBufferAble $connect
     *
     * @return int|false
     *          int - 数据包长度（0-没有获取到长度）
     *          false - 数据包错误，需要关闭当前链接
     * @author liu.bin 2020-05-19 16:29
     */
    public function framePoint($buffer,ReadBufferAble $connect)
    {

        if(empty($buffer)){
            return false;
        }

        $pos = strpos($buffer, PHP_EOL);
        if(false !== $pos){
            return $pos + 1;
        }
        return 0;
    }

    
    /**
     * 解包 格式化输出数据包的内容
     *
     * @param string $buffer
     * @return string
     */
    public function decode($buffer,ConnectAble $connect=null)
    {
        return trim($buffer);
    }


    /**
     * 打包
     *
     * @param string $buffer
     * @return string
     */
    public function encode($buffer,ConnectAble $connect = null)
    {
        return $buffer.PHP_EOL;
    }
}
